import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'


const ready = ref(false)
const config = ref({
    url: import.meta.env.VITE_SERVER_URL,
})
const queueMsg = ref([])  // 排队的消息
const enable_message = ref(false)  // 第一次不提示

async function sendRequest(msg, suffix='') {
    try {
        const response = await fetch(config.value.url + suffix, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: msg
        })
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const data = await response.json()
        return data
    } catch (error) {
        console.error('请求错误:', error)
        throw error
    }
}

async function checkServerStatus() {
    try {
        await fetch(config.value.url)
        ready.value = true
        enable_message.value = true
        if (document.getElementById(config.value.notice_label)) {
            document.getElementById(config.value.notice_label).style.display = 'none'
        }
        // 处理队列中的消息
        while (queueMsg.value.length > 0) {
            const msg = queueMsg.value.pop()
            await sendRequest(msg)
        }
    } catch (error) {
        ready.value = false
        if (enable_message.value) {
            enable_message.value = false
            Message.warning({
                content: '服务连接失败! 正在尝试重新连接...',
                duration: 6000,
                onClose: () => {
                    checkServerStatus()
                }
            })
            if (document.getElementById(config.value.notice_label)) {
                document.getElementById(config.value.notice_label).style.display = 'flex'
            }
            config.value.onClose()
        } else {
            setTimeout(() => {
                enable_message.value = true
                checkServerStatus()
            }, 6000)
        }
    }
}

export default {
    init(cfg) {
        config.value = cfg
        checkServerStatus()
    },

    ready() {
        return ready.value
    },

    async readConfig() {
        try {
            const jsonObject = {
                "method": "ReadConfig",
                "args": {}
            }
            const jsonString = JSON.stringify(jsonObject)
            return await sendRequest(jsonString)
        } catch (error) {
            console.error('读取配置失败:', error)
            throw error
        }
    },

    async saveConfig(msg) {
        try {
            const jsonString = JSON.stringify(msg)
            return await sendRequest(jsonString)
        } catch (error) {
            console.error('写入配置失败:', error)
            throw error
        }
    },

    sendMsg(msg) {
        if (ready.value) {
            return sendRequest(msg)
        } else {
            queueMsg.value.push(msg)
        }
    },

    bindRecvMsg(callback) {
        config.value.onMessage = callback
    },

    async removeBG(msg) {
        try {
            const jsonString = JSON.stringify(msg)
            return await sendRequest(jsonString)
        } catch (error) {
            console.error('移除背景失败:', error)
            throw error
        }
    },

    async saveImage(msg) {
        try {
            const jsonString = JSON.stringify(msg)
            return await sendRequest(jsonString)
        } catch (error) {
            console.error('保存图片失败:', error)
            throw error
        }
    },

    async do(msg, suffix='') {
        try {
            const jsonString = JSON.stringify(msg)
            return await sendRequest(jsonString, suffix)
        } catch (error) {
            console.error('执行失败:', error)
            throw error
        }
    }
}